import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import message from '@/components/common/message'
import { getTeacherInfo, updateTeacherInfo } from '@/request/teacher'

export const useTeacherStore = defineStore('teacher', () => {
  // state
  const teacher = ref({
    id: -1,
    timestamp: '',
    birthday: '',
    gender: '',
    name: '未知',
    phone: '',
    school: '未知',
    stageType: 0,
    teacherId: '',
    dueDate: '',
    title: null as string | null,
    email: null as string | null,
  })
  const isLoading = ref(true)
  const error = ref<string | null>(null)
  const lastFetchTime = ref(0)
  let callbacks: (() => unknown)[] = []

  // getters
  const teacherName = computed(() => teacher.value.name)
  const teacherSchool = computed(() => teacher.value.school)

  // actions
  async function fetchInfo() {
    isLoading.value = true
    try {
      const data = await getTeacherInfo()
      teacher.value = {
        ...teacher.value,
        ...data.entry,
      }
      lastFetchTime.value = Date.now()
      callbacks.forEach(i => i.apply(undefined))
      callbacks = []
      return data.entry
    }
    catch (err) {
      error.value = err instanceof Error ? err.message : '获取教师信息失败'
      message.error(error.value)
      return teacher.value
    }
    finally {
      isLoading.value = false
    }
  }

  async function updateInfo(teacherInfo: {
    birthday: string
    gender: string
    name: string
    phone: string
    school: string
    stageType: number
  }) {
    if (isLoading.value)
      return null

    isLoading.value = true
    error.value = null

    try {
      const data = await updateTeacherInfo({
        ...teacherInfo,
        data: teacherInfo.phone,
      })
      teacher.value = {
        ...teacher.value,
        ...data.entry,
        phone: teacherInfo.phone,
      }
      lastFetchTime.value = Date.now()
      callbacks.forEach(i => i.apply(undefined))
      callbacks = []
      return data.entry
    }
    catch (err) {
      error.value = err instanceof Error ? err.message : '更新教师信息失败'
      message.error(error.value)
      return null
    }
    finally {
      isLoading.value = false
    }
  }

  function resetError() {
    error.value = null
  }

  function addCallback(fn: () => unknown) {
    if (!isLoading.value) {
      fn.apply(undefined)
      return
    }
    callbacks.push(fn)
  }

  return {
    teacher,
    isLoading,
    error,
    lastFetchTime,
    teacherName,
    teacherSchool,
    fetchInfo,
    updateInfo,
    resetError,
    addCallback,
  }
})
